package com.heima.article.interceotpr;

import com.alibaba.nacos.api.utils.StringUtils;
import com.heima.common.Constants;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //return HandlerInterceptor.super.preHandle(request, response, handler);
        //业务方法执行之前，先执行preHandle
        // 获取请求头中的userId
        String userId = request.getHeader(Constants.HEADER_KEY_USERID);
        if(StringUtils.isEmpty(userId)){
            log.error("没有获取得到userId-----,uri:{}", request.getRequestURI());
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 存入ThreadLocal
        UserThreadLocalUtils.setUserId(Integer.valueOf(userId));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        //业务方法执行之后，执行postHandle，如果业务方法执行的时候出现了异常，此方法不回调
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //业务方法执行之后，执行afterCompletion，如果业务方法执行的时候出现了异常，此方法会回调
        // 清空ThreadLocal
        UserThreadLocalUtils.removeUser();
    }
}
